---
title: Monitor the network state to reduce latency
---


Android and Apple targets provide APIs to monitor the network state of your device:

- [ConnectivityManager](https://developer.android.com/training/monitoring-device-state/) on Android targets.
- [NWPathMonitor](https://developer.apple.com/documentation/network/nwpathmonitor) on Apple targets.

You can configure your [ApolloClient](https://www.apollographql.com/docs/kotlin/kdoc/apollo-runtime/com.apollographql.apollo/-apollo-client/index.html) to use these APIs to improve latency of your requests using the `NetworkMonitor` API:

```kotlin
// androidMain
val networkMonitor = NetworkMonitor(context)

// appleMain
val networkMonitor = NetworkMonitor()

// commonMain
val apolloClient = ApolloClient.Builder()
    .serverUrl("https://example.com/graphql")
    .retryOnErrorInterceptor(RetryOnErrorInterceptor(networkMonitor))
    .build()

// once you're done with your `ApolloClient`
networkMonitor.close()
```

### `failFastIfOffline`

When a `NetworkMonitor` is configured, you can use `failFastIfOffline` to avoid trying out request if the device is offline:

```kotlin
// Opt-in `failFastIfOffline` on all queries
val apolloClient = ApolloClient.Builder()
    .serverUrl("https://example.com/graphql")
    .retryOnErrorInterceptor(RetryOnErrorInterceptor(networkMonitor))
    .failFastIfOffline(true)
    .build()

val response = apolloClient.query(myQuery).execute()
println(response.exception?.message)
// "The device is offline"

// Opt-out `failFastIfOffline` on a single query
val response = apolloClient.query(myQuery).failFastIfOffline(false).execute()
```

### `retryOnError`

When a `NetworkMonitor` is configured, `retryOnError` uses `NetworkMonitor.waitForNetwork()` instead of the default exponential backoff algorithm in order to reconnect faster when connectivity is back.

### Customizing the retry algorithm

To customize the retry algorithm, use a `RetryStrategy`. The following example shows a `RetryStrategy` that uses exponential backoff and gives up after four tries: 

```kotlin
val apolloClient = ApolloClient.Builder()
    .retryOnErrorInterceptor(RetryOnErrorInterceptor(networkMonitor) { state, request, response,  ->
      val exception = response.exception
      if (exception == null) {
        return@RetryOnErrorInterceptor false
      }

      delay(2.0.pow(state.attempt).seconds)
      state.attempt++
      return@RetryOnErrorInterceptor state.attempt < 4
    })
    .build()
```

